<template>
  <div class="config-check">
    <div class="config-header">
      <h3>API配置检查</h3>
      <button class="check-btn" @click="checkConfig" :disabled="checking">
        {{ checking ? '检查中...' : '检查配置' }}
      </button>
    </div>
    
    <div class="config-results">
      <div class="config-item">
        <h4>基础配置</h4>
        <div class="config-detail">
          <div class="item">
            <span class="label">AppKey:</span>
            <span class="value">{{ config.appKey }}</span>
            <span class="status" :class="baseStatus">{{ baseStatus }}</span>
          </div>
          <div class="item">
            <span class="label">Sign:</span>
            <span class="value">{{ config.sign.substring(0, 20) }}...</span>
          </div>
        </div>
      </div>

      <div class="config-item">
        <h4>工作表配置</h4>
        <div class="config-detail">
          <div class="item">
            <span class="label">拣货单表ID:</span>
            <span class="value">{{ config.pickingWorksheetId }}</span>
            <span class="status" :class="supplierStatus">{{ supplierStatus }}</span>
          </div>
          <div class="item">
            <span class="label">拣货单视图ID:</span>
            <span class="value">{{ config.pickingViewId }}</span>
          </div>
          <div class="item">
            <span class="label">拣货详情表ID:</span>
            <span class="value">{{ config.pickingDetailWorksheetId }}</span>
          </div>
        </div>
      </div>

      <div class="config-item">
        <h4>字段配置</h4>
        <div class="config-detail">
          <div class="item">
            <span class="label">供应商名称字段:</span>
            <span class="value">{{ config.supplierNameField }}</span>
          </div>
          <div class="item">
            <span class="label">订单ID字段:</span>
            <span class="value">{{ config.orderIdField }}</span>
          </div>
          <div class="item">
            <span class="label">状态字段:</span>
            <span class="value">{{ config.statusField }}</span>
          </div>
          <div class="item">
            <span class="label">拣货数量字段:</span>
            <span class="value">{{ config.quantityField }}</span>
          </div>
        </div>
      </div>

      <div v-if="testResults.length > 0" class="test-results">
        <h4>测试结果</h4>
        <div v-for="result in testResults" :key="result.test" class="test-item">
          <span class="test-name">{{ result.test }}</span>
          <span class="test-status" :class="result.status">{{ result.status }}</span>
          <span class="test-message">{{ result.message }}</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import wmsApi from '../api/index.js'
import { API_CONFIG, WORKSHEET_IDS, VIEW_IDS, SUPPLIER_FIELDS, QUANTITY_FIELDS } from '../config/wms-config.js'

const checking = ref(false)
const baseStatus = ref('未检查')
const supplierStatus = ref('未检查')
const testResults = ref([])

const config = ref({
  appKey: API_CONFIG.appKey,
  sign: API_CONFIG.sign.substring(0, 20) + '...',
  pickingWorksheetId: WORKSHEET_IDS.PICKING_ORDERS,
  pickingViewId: VIEW_IDS.PICKING_ORDERS_DEFAULT,
  pickingDetailWorksheetId: WORKSHEET_IDS.PICKING_DETAILS,
  supplierNameField: SUPPLIER_FIELDS.NAME,
  orderIdField: 'N/A',
  statusField: QUANTITY_FIELDS.STATUS,
  quantityField: QUANTITY_FIELDS.PICKED
})

async function checkConfig() {
  checking.value = true
  testResults.value = []
  
  try {
    // 验证API配置
    await validateApiConfig()
    
    // 测试基础连接
    await testBasicConnection()
    
    // 测试拣货单数据获取
    await testSupplierData()
    
  } catch (error) {
    console.error('配置检查失败:', error)
  } finally {
    checking.value = false
  }
}

async function validateApiConfig() {
  try {
    const validation = wmsApi.validateConfiguration()
    
    if (validation.isValid) {
      testResults.value.push({
        test: 'API配置验证',
        status: 'success',
        message: '所有必要配置项已设置'
      })
    } else {
      testResults.value.push({
        test: 'API配置验证',
        status: 'error',
        message: `配置问题: ${validation.issues.join(', ')}`
      })
    }
  } catch (error) {
    testResults.value.push({
      test: 'API配置验证',
      status: 'error',
      message: `验证失败: ${error.message}`
    })
  }
}

async function testBasicConnection() {
  try {
    console.log('开始基础连接测试...')
    
    // 使用新的测试连接方法
    const result = await wmsApi.testConnection()
    console.log('基础连接测试结果:', result)
    
    if (result.success) {
      baseStatus.value = '正常'
      testResults.value.push({
        test: '基础连接测试',
        status: 'success',
        message: '明道云API连接正常'
      })
      
      // 显示响应的数据结构信息
      if (result.data) {
        const dataInfo = `返回数据结构: ${Object.keys(result.data).join(', ')}`
        testResults.value.push({
          test: '响应数据结构',
          status: 'info',
          message: dataInfo
        })
      }
    } else {
      baseStatus.value = '失败'
      testResults.value.push({
        test: '基础连接测试',
        status: 'error',
        message: `连接失败: ${result.error}`
      })
    }
  } catch (error) {
    console.error('基础连接测试失败:', error)
    baseStatus.value = '失败'
    testResults.value.push({
      test: '基础连接测试',
      status: 'error',
      message: `连接失败: ${error.message}`
    })
  }
}

async function testSupplierData() {
  try {
    console.log('开始拣货单数据测试...')
    const result = await wmsApi.getSuppliers()
    console.log('配置检查-拣货单数据:', result)
    
    if (result && result.rows && result.rows.length > 0) {
      supplierStatus.value = '正常'
      
      // 显示第一条数据的字段信息，帮助调试
      const firstRow = result.rows[0]
      const fieldNames = firstRow.controls ? firstRow.controls.map(c => c.controlName || c.controlId).join(', ') : '无字段'
      
      testResults.value.push({
        test: '拣货单数据获取',
        status: 'success',
        message: `获取到 ${result.rows.length} 条拣货单数据`
      })
      
      testResults.value.push({
        test: '拣货单字段检查',
        status: 'info',
        message: `可用字段: ${fieldNames}`
      })
      
      // 检查供应商字段
      const supplierField = firstRow.controls ? firstRow.controls.find(c => 
        c.controlId === '6878abc6a462f1cb468b42e3' || 
        c.controlName === '供应商名称' || 
        c.controlName === '供应商'
      ) : null
      
      if (supplierField) {
        testResults.value.push({
          test: '供应商字段检查',
          status: 'success',
          message: `找到供应商字段: ${supplierField.controlName || supplierField.controlId}, 值: ${supplierField.value || '空'}`
        })
      } else {
        testResults.value.push({
          test: '供应商字段检查',
          status: 'warning',
          message: '未找到供应商字段，请检查字段配置'
        })
      }
      
    } else if (result && result.rows && result.rows.length === 0) {
      supplierStatus.value = '无数据'
      testResults.value.push({
        test: '拣货单数据获取',
        status: 'warning',
        message: '视图中没有数据，请检查明道云工作表是否有记录'
      })
    } else {
      supplierStatus.value = '无数据'
      testResults.value.push({
        test: '拣货单数据获取',
        status: 'warning',
        message: '未获取到拣货单数据，响应格式可能不正确'
      })
    }
  } catch (error) {
    console.error('拣货单数据测试失败:', error)
    supplierStatus.value = '失败'
    testResults.value.push({
      test: '拣货单数据获取',
      status: 'error',
      message: `获取失败: ${error.message}`
    })
  }
}

async function testPickingData() {
  try {
    // 使用第一个供应商测试拣货单数据
    const supplierResult = await wmsApi.getSuppliers()
    if (supplierResult && supplierResult.rows && supplierResult.rows.length > 0) {
      const firstSupplier = supplierResult.rows[0]
      const pickingResult = await wmsApi.getPickingOrders(firstSupplier.rowid)
      console.log('配置检查-拣货单数据:', pickingResult)
      
      if (pickingResult && pickingResult.rows && pickingResult.rows.length > 0) {
        const firstOrder = pickingResult.rows[0]
        const orderFieldNames = firstOrder.controls ? firstOrder.controls.map(c => c.controlName || c.controlId).join(', ') : '无字段'
        
        testResults.value.push({
          test: '拣货单数据获取',
          status: 'success',
          message: `获取到 ${pickingResult.rows.length} 条拣货单数据`
        })
        
        testResults.value.push({
          test: '拣货单字段检查',
          status: 'info',
          message: `可用字段: ${orderFieldNames}`
        })
      } else {
        testResults.value.push({
          test: '拣货单数据获取',
          status: 'warning',
          message: '供应商暂无拣货单数据'
        })
      }
    }
  } catch (error) {
    testResults.value.push({
      test: '拣货单数据获取',
      status: 'error',
      message: `获取失败: ${error.message}`
    })
  }
}

onMounted(() => {
  // 页面加载时自动检查一次配置
  checkConfig()
})
</script>

<style scoped>
.config-check {
  background: white;
  border-radius: 8px;
  padding: 1.5rem;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  margin: 1rem;
}

.config-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 2rem;
  padding-bottom: 1rem;
  border-bottom: 2px solid #f0f0f0;
}

.config-header h3 {
  color: #333;
  margin: 0;
}

.check-btn {
  background: #f8b300;
  color: white;
  border: none;
  padding: 0.75rem 1.5rem;
  border-radius: 6px;
  cursor: pointer;
  font-weight: 500;
  transition: background-color 0.2s;
}

.check-btn:hover:not(:disabled) {
  background: #e6a200;
}

.check-btn:disabled {
  background: #ccc;
  cursor: not-allowed;
}

.config-item {
  margin-bottom: 2rem;
}

.config-item h4 {
  color: #333;
  margin-bottom: 1rem;
  font-size: 1.1rem;
}

.config-detail .item {
  display: flex;
  align-items: center;
  margin-bottom: 0.75rem;
  padding: 0.5rem;
  background: #f9f9f9;
  border-radius: 4px;
}

.item .label {
  font-weight: 600;
  color: #555;
  width: 150px;
  flex-shrink: 0;
}

.item .value {
  flex: 1;
  color: #666;
  font-family: monospace;
  font-size: 0.9rem;
}

.item .status {
  padding: 0.25rem 0.75rem;
  border-radius: 12px;
  font-size: 0.8rem;
  font-weight: 500;
  margin-left: 1rem;
}

.status.正常, .test-status.success {
  background: #d4edda;
  color: #155724;
}

.status.失败, .test-status.error {
  background: #f8d7da;
  color: #721c24;
}

.status.无数据, .test-status.warning {
  background: #fff3cd;
  color: #856404;
}

.status.未检查 {
  background: #e9ecef;
  color: #6c757d;
}

.test-status.info {
  background: #d1ecf1;
  color: #0c5460;
}

.test-results {
  margin-top: 2rem;
  padding-top: 1rem;
  border-top: 2px solid #f0f0f0;
}

.test-item {
  display: flex;
  align-items: center;
  margin-bottom: 0.75rem;
  padding: 0.75rem;
  background: #f9f9f9;
  border-radius: 6px;
}

.test-name {
  font-weight: 600;
  color: #333;
  width: 150px;
  flex-shrink: 0;
}

.test-status {
  padding: 0.25rem 0.75rem;
  border-radius: 12px;
  font-size: 0.8rem;
  font-weight: 500;
  margin-right: 1rem;
}

.test-message {
  flex: 1;
  color: #666;
}
</style>